package com.whjz.dcfs.util;

import java.net.URLDecoder;
import java.net.URLEncoder;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CookieUtil {
	private static String path = "/dcfs";
	private static int default_age = 30*24*3600;//一个月
	/**
	 * 添加cookie
	 */
	public static void addCookie(String name,String value,int age,HttpServletResponse response){
		addCookie(path,name, value, age, response);
	}
	
	public static void addCookie(String path,String name,String value,int age,HttpServletResponse response){
		try {
			Cookie cookie = new Cookie(name,URLEncoder.encode(value,"utf-8"));
			cookie.setPath(path);
			cookie.setMaxAge(age);
			response.addCookie(cookie);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static void addCookie(String name,String value,HttpServletResponse response){
		addCookie(name, value, default_age, response);
	}
	/**
	 * 删除cookie
	 */
	public static void deleteCookie(String name,HttpServletResponse response){
		deleteCookie(path, name, response);
	}
	
	public static void deleteCookie(String path,String name,HttpServletResponse response){
		Cookie cookie = new Cookie(name,"");
		cookie.setPath(path);
		cookie.setMaxAge(0);
		response.addCookie(cookie);
	}
	/**
	 * 查找cookie
	 */
	public static String findCookie(String name,HttpServletRequest request){
		Cookie[] cookies = request.getCookies();
		if(cookies!=null){
			for (Cookie cookie : cookies) {
				if(cookie.getName().equals(name)){
					try {
						return URLDecoder.decode(cookie.getValue(),"utf-8");
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		}
		return "0";
	}
}
